<?php
/**
 * topTracks.php
 *
 * INPUT: 	$_REQUEST['country']
 *			$_REQUEST['limit']
 * OUTPUT: 	an XML file with the most popular tracks in a given country.
 *
 * Speaks for its own I hope.
 * 
 * By Laurens Van Keer
 */
require 'auth.php';
	
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' . PHP_EOL;
echo '<TopTracks>' . PHP_EOL;

$apiClass = new lastfmApi();
$artistClass = $apiClass->getPackage($auth, 'artist', $config);
$geoClass = $apiClass->getPackage($auth, 'geo', $config);

$country = addslashes(strip_tags($_REQUEST['country']));
$reqLimit = addslashes(strip_tags($_REQUEST['limit']));

if ( empty($country) ) {
	echo '<Error>No country specified!</Error>' . PHP_EOL;
} else {

	$methodVars = array(
		'country' => $country
	);

	if ( $tracks = $geoClass->getTopTracks($methodVars) ) {
	
		$limit = sizeof($tracks);
		if ( ! empty($reqLimit) ) {
			$limit = $reqLimit>$limit?$limit:$reqLimit;
		}
		
		for ($i=0; $i<$limit; $i++) {
			// get thumbnail url
			$thumbnail_medium = $tracks[$i]['image']['medium'];
			$thumbnail_large = $tracks[$i]['image']['large'];
			if ( empty($thumbnail_medium) ) {
				$artistVars = array( 'artist' => $tracks[$i]['artist']['name'] );
				$artistInfo = $artistClass->getInfo($artistVars);
				$thumbnail_medium = $artistInfo['image']['medium'];
				$thumbnail_large = $artistInfo['image']['large'];
			}
			
			// build xml
			echo '<Track>' . PHP_EOL;
				echo "<Id>$i</Id>" . PHP_EOL;
				echo '<Title>' . htmlentities($tracks[$i]['name']) . '</Title>' . PHP_EOL;
				echo '<Artist>' . htmlentities($tracks[$i]['artist']['name']) . '</Artist>' . PHP_EOL;
				echo '<Rank>' . htmlentities($tracks[$i]['rank']) . '</Rank>' . PHP_EOL;
				echo '<Thumbnail>' . PHP_EOL;
					echo '<Medium>' . htmlentities($thumbnail_medium) . '</Medium>' . PHP_EOL;
					echo '<Large>' . htmlentities($thumbnail_large) . '</Large>' . PHP_EOL;
				echo '</Thumbnail>' . PHP_EOL;
			echo '</Track>' . PHP_EOL;
		}
		
	} else {
		echo '<Error>Error ' . $geoClass->error['code'] . ' - ' . $geoClass->error['desc'] . '</Error>' . PHP_EOL;
	}
	
}

echo '</TopTracks>' . PHP_EOL;
?>